package com.wanlian.net.File;

import com.wanlian.json.JsonStringUtil;
import com.wanlian.netty.File.model.BaseHead;
import com.wanlian.netty.File.model.FileHead;
import com.wanlian.netty.File.msg.FileBaseMsg;
import com.wanlian.netty.File.msg.FilePeerMsg;
import com.wanlian.netty.File.msg.FilePeerMsgQueue;
import com.wanlian.netty.File.msg.down.FilePeerDownMsg;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Handles a client-side channel.
 */
public class DeviceClientFileHandler extends ChannelInboundHandlerAdapter { // (1)
    private Logger logger = LoggerFactory.getLogger(getClass());
    private final ByteBuf firstMessage;

    public DeviceClientFileHandler() {
        byte[] req = "Hello from client".getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            FilePeerMsg filePeerMsg = (FilePeerMsg) msg;
            FileBaseMsg baseMsg = filePeerMsg.getFileBaseMsg();
            String msgType = baseMsg.getType();
            System.out.println(JsonStringUtil.writeValueAsString(baseMsg));
            if(msgType.equals("DEVICE_FILE_DOWNLOAD_RSP")){
                String content = baseMsg.getContent();
                BaseHead baseHead = JsonStringUtil.readValue(content, BaseHead.class);
                String headInfo = baseHead.getContent();
                FileHead head = JsonStringUtil.readValue(headInfo, FileHead.class);
                System.out.println("size:"+head.getSize()+"offset:"+head.getOffset());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        logger.error("client caught exception", cause);
        ctx.close();
    }
}